package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import cn.hutool.core.collection.CollectionUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.hig.component.GsonUtil;
import com.hig.exam.domain.RangesDto;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.read.mapper.SysNoticeReadMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.SysNotice;
import com.ruoyi.system.service.ISysNoticeService;

/**
 * 公告 信息操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/notice")
public class SysNoticeController extends BaseController
{
    @Autowired
    private ISysNoticeService noticeService;
    @Autowired
    private SysNoticeReadMapper noticeReadMapper;
    @Autowired
    private TokenService tokenService;

    /**
     * 获取通知公告列表
     */

    @GetMapping("/list")
    public TableDataInfo list(SysNotice notice)
    {
        startPage();
        List<SysNotice> list = noticeService.selectNoticeList(notice);
        return getDataTable(list);
    }
    @Autowired
    private ISysDeptService deptService;

    @GetMapping("/listNoPage")
    public TableDataInfo listNoPage(SysNotice notice)
    {
        Gson gson = new Gson();

//        startPage();
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        Long userId = loginUser.getUser().getUserId();
        List<SysNotice> list = noticeReadMapper.getUnreadNoticesByUserId(userId);
        if (CollectionUtil.isEmpty(list)){
            list=new ArrayList<SysNotice>();
        }
        for (SysNotice sysNotice : list) {
            String noticeType = sysNotice.getNoticeType();
            if (StringUtils.isNotEmpty(noticeType)&&"2".equals(noticeType)){
                continue;
            }
            ArrayList<Object> dArray = new ArrayList<>();
            String users = sysNotice.getUsers();

            String depts = sysNotice.getDepts();
            List<Long> deptList = gson.fromJson(depts, new TypeToken<List<Long>>(){}.getType());
            Long deptId = loginUser.getUser().getDeptId();
            SysDept sysDept = deptService.selectDeptById(deptId);
            String ancestors = sysDept.getAncestors();
            String[] split = ancestors.split(",");
            List<Long> userList = gson.fromJson(users, new TypeToken<List<Long>>(){}.getType());

            dArray.add(deptId);
            for (String s : split) {
                dArray.add(Long.valueOf(s));
            }
            Integer du = sysNotice.getDu();

            if (du==0){
                //部门
                boolean hasCommon = deptList.stream().anyMatch(dArray::contains);
                if (!hasCommon){
                    list.remove(sysNotice);
                }
            }else {
                //人员
                if (!userList.contains(userId)){
                    list.remove(sysNotice);
                }
            }
            if (list.size()==0){
                return getDataTable(list);
            }
//            if ((CollectionUtil.isNotEmpty(userList)&&!userList.contains(userId))&& (CollectionUtil.isNotEmpty(deptList)&&!deptList.contains(dArray))) {
//                list.remove(sysNotice);
//            }
        }
        return getDataTable(list);
    }
    /**
     * 根据通知公告编号获取详细信息
     */

    @GetMapping(value = "/{noticeId}")
    public AjaxResult getInfo(@PathVariable Long noticeId)
    {
        return AjaxResult.success(noticeService.selectNoticeById(noticeId));
    }

    /**
     * 新增通知公告
     */

    @Log(title = "通知公告", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody SysNotice notice)
    {
        List<Long> noticeDepts = notice.getNoticeDepts();
        List<Long> noticeUsers = notice.getNoticeUsers();
        Gson gson = new Gson();
        if (CollectionUtil.isNotEmpty(noticeDepts)){
            String noticeDeptsjson = gson.toJson(noticeDepts);
            notice.setDepts(noticeDeptsjson);
        }
        if (CollectionUtil.isNotEmpty(noticeUsers)){
            String noticeUsersjson = gson.toJson(noticeUsers);
            notice.setUsers(noticeUsersjson);
        }
        String noticeType = notice.getNoticeType();
        if (noticeType.equals("1")){
            Integer du = notice.getDu();
            if (du==0){
              if (CollectionUtil.isEmpty( notice.getNoticeDepts()) ){
                  throw new RuntimeException("请选择通知部门");
              }
            }
            if (du==1){
                if (CollectionUtil.isEmpty( notice.getNoticeUsers()) ){
                    throw new RuntimeException("请选择通知用户");
                }
            }
        }
        notice.setCreateBy(SecurityUtils.getUsername());
        return toAjax(noticeService.insertNotice(notice));
    }

    /**
     * 修改通知公告
     */

    @Log(title = "通知公告", businessType = BusinessType.UPDATE)
    @PostMapping("/update")
    // @PutMapping
    public AjaxResult edit(@Validated @RequestBody SysNotice notice)
    {
        List<Long> noticeDepts = notice.getNoticeDepts();
        List<Long> noticeUsers = notice.getNoticeUsers();
        Gson gson = new Gson();
        if (CollectionUtil.isNotEmpty(noticeDepts)){
            String noticeDeptsjson = gson.toJson(noticeDepts);
            notice.setDepts(noticeDeptsjson);
        }
        if (CollectionUtil.isNotEmpty(noticeUsers)){
            String noticeUsersjson = gson.toJson(noticeUsers);
            notice.setUsers(noticeUsersjson);
        }
        notice.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(noticeService.updateNotice(notice));
    }

    /**
     * 删除通知公告
     */

    @Log(title = "通知公告", businessType = BusinessType.DELETE)
    @GetMapping("/batch/{noticeIds}")
    // @DeleteMapping("/{noticeIds}")
    public AjaxResult remove(@PathVariable Long[] noticeIds)
    {
        return toAjax(noticeService.deleteNoticeByIds(noticeIds));
    }
}
